﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Elderos.AI;
using Elderos.Highlight.Search;
using Encog.ML.Data.Basic;
using Encog.Neural.Networks;

namespace Elderos.Highlight
{
    public class NeuralAmbiguityResolver : ThresholdAmbiguityResolver
    {
        private BasicNetwork _network;
        private INormalizer _normalizer;

        public NeuralAmbiguityResolver(double activationThreshold, BasicNetwork network, INormalizer normalizer) : base(activationThreshold)
        {
            _network = network;
            _normalizer = normalizer;
        }

        public override void Process(IEnumerable<Position> positions)
        {
            foreach (var entityInfo in positions)
            {
                ProcessPosition(entityInfo);
            }
        }

        public override IAmbiguityResolver Clone()
        {
            return new NeuralAmbiguityResolver(ActivationThreshold, (BasicNetwork)_network.Clone(), _normalizer);
        }

        private void ProcessPosition(Position position)
        {
            foreach (var textEntity in position.Entities)
            {
                var vector = _normalizer.Normalize(textEntity.FactorVector);
                textEntity.ResultCoef = _network.Compute(new BasicMLData(vector))[0];
            }

            var winner = position.Entities.OrderByDescending(x => x.ResultCoef).First();
            if (winner.ResultCoef > ActivationThreshold)
                position.Winner = winner;
        }
    }
}
